<template>
  <div class="analytics-container">
    <!-- 统计卡片区域 -->
    <div class="stats-grid">
      <div 
        class="stat-card" 
        v-for="(item, index) in BoxData" 
        :key="index"
        :class="`stat-card-${index + 1}`"
      >
        <div class="stat-card-content">
          <div class="stat-card-header">
            <h3>{{ item.title }}</h3>
            <SvgIcon
              class="stat-icon"
              prefix="#icon-back-"
              :name="item.icon"
              width="60px"
              height="60px"
            />
          </div>
          <div class="stat-card-value">
            <span class="count-number">{{ item.count }}</span>
          </div>
          <div class="stat-card-footer">
            <span class="label">总用户量</span>
            <span class="total-value">{{ item.count * 100 }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="chart-section">
      <el-card class="chart-card">
        <template #header>
          <div class="chart-header">
            <h3 class="chart-title">浏览量数据统计</h3>
            <el-button-group class="time-filter">
              <el-button 
                :type="type1" 
                @click="handleClick('day')"
                class="filter-btn"
              >日</el-button>
              <el-button 
                :type="type2" 
                @click="handleClick('month')"
                class="filter-btn"
              >月</el-button>
              <el-button 
                :type="type3" 
                @click="handleClick('year')"
                class="filter-btn"
              >年</el-button>
            </el-button-group>
          </div>
        </template>
        
        <div class="chart-type-selector">
          <el-button 
            class="chart-type-btn" 
            :class="{ 'active': chartType === 'bar' }"
            @click="changeType('bar')"
          >
            <i class="el-icon-data-analysis"></i> 柱状图
          </el-button>
          <el-button 
            class="chart-type-btn" 
            :class="{ 'active': chartType === 'line' }"
            @click="changeType('line')"
          >
            <i class="el-icon-data-line"></i> 折线图
          </el-button>
        </div>
        
        <div class="chart-container">
          <div v-if="!dataLoaded" class="chart-loading">
            <el-skeleton :rows="6" animated />
          </div>
          <div ref="chart" class="echarts-container"></div>
        </div>
      </el-card>
    </div>

    <!-- 地图区域 -->
    <div class="geo-section">
      <el-card class="geo-card">
        <EchartGeo></EchartGeo>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import SvgIcon from '@/components/SvgIcon/SvgIcon.vue'
import { onMounted, ref, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import {
  countIPAddressSync,
  getAllUserCountSync,
  getArticlesCountSync,
  getCommentsCountSync,
  getIpAddressListByDateSync,
  getIpAddressListByMonthSync,
  getIpAddressListByYearSync,
} from '@/api/manage'
import EchartGeo from '@/views/manage/analytics/echart-geo.vue'

// 图表引用
const chart = ref(null)
let myChart: any

// 数据状态
let BoxData = ref([])
const dataLoaded = ref(false)
const chartType = ref('line')

// 时间筛选按钮状态
let type1 = ref<string>('success')
let type2 = ref<string>('primary')
let type3 = ref<string>('primary')

// 数据类型定义
type IpAddressListByDateItem = {
  data: string
  total_count: number
}
let IpAddressListByDate = ref<[IpAddressListByDateItem]>([])

// 生命周期钩子
onMounted(async () => {
  // 初始化数据
  await Promise.all([
    getUserCount(),
    getArticlesCount(),
    getCommentsCount(),
    getCountIPAddress()
  ])
  
  // 初始化图表
  await initChart()
  
  // 添加 resize 事件监听
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  // 移除事件监听
  window.removeEventListener('resize', resizeChart)
  // 销毁图表实例
  if (myChart) {
    myChart.dispose()
  }
})

// 数据获取方法
const getIpAddressListByDate = async () => {
  let res = await getIpAddressListByDateSync()
  IpAddressListByDate.value = res.data
  return res.data
}

const getIpAddressListByMonth = async () => {
  let res = await getIpAddressListByMonthSync()
  IpAddressListByDate.value = res.data
  return res.data
}

const getIpAddressListByYear = async () => {
  let res = await getIpAddressListByYearSync()
  IpAddressListByDate.value = res.data
  return res.data
}

// 图表初始化
const initChart = async () => {
  if (!chart.value) return
  
  myChart = echarts.init(chart.value)
  myChart.showLoading() // 显示加载动画
  
  try {
    await getIpAddressListByDate()
    dataLoaded.value = true // 数据已加载
    updateChart()
  } catch (error) {
    console.error('加载图表数据失败:', error)
  } finally {
    myChart.hideLoading() // 隐藏加载动画
  }
}

// 更新图表
const updateChart = () => {
  if (!dataLoaded.value || !IpAddressListByDate.value.length) return
  
  const xAxisData = IpAddressListByDate.value.map((item) => item.data)
  const seriesData = IpAddressListByDate.value.map((item) => item.total_count)
  
  // 设置图表配置项
  myChart.setOption({
    backgroundColor: '#fff',
    title: {
      text: '浏览量数据统计',
      left: 'center',
      top: '5%',
      textStyle: {
        color: '#333',
        fontSize: 18,
        fontWeight: 'bold'
      },
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(50,50,50,0.8)',
      borderColor: '#ccc',
      borderWidth: 1,
      textStyle: { color: '#fff' },
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba(150,150,150,0.1)'
        }
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLine: { lineStyle: { color: '#aaa' } },
      axisLabel: { 
        color: '#333',
        rotate: xAxisData.length > 12 ? 45 : 0,
        margin: 15
      },
      boundaryGap: chartType.value === 'bar'
    },
    yAxis: {
      type: 'value',
      axisLine: { lineStyle: { color: '#aaa' } },
      axisLabel: { color: '#333' },
      splitLine: { lineStyle: { color: '#eee' } },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true,
    },
    toolbox: {
      show: true,
      feature: {
        saveAsImage: { title: '保存为图片' },
        dataView: { title: '数据视图', readOnly: false },
        restore: { title: '还原' },
        dataZoom: { title: '区域缩放', yAxisIndex: 'none' },
        magicType: {
          type: ['line', 'bar'],
          title: { line: '切换折线图', bar: '切换柱状图' },
        },
      },
      iconStyle: {
        borderColor: '#333',
      },
      emphasis: {
        iconStyle: {
          borderColor: '#666',
        },
      },
    },
    series: [
      {
        name: '访问量',
        type: chartType.value,
        data: seriesData,
        smooth: chartType.value === 'line',
        showBackground: chartType.value === 'bar',
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.1)'
        },
        markPoint: {
          data: [{ type: 'max', name: '最大值' }],
          symbol: 'pin',
          symbolSize: 50,
          itemStyle: {
            color: '#ff5722'
          }
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#42a5f5' },
            { offset: 0.5, color: '#1e88e5' },
            { offset: 1, color: '#0d47a1' },
          ]),
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.2)',
          borderRadius: chartType.value === 'bar' ? 4 : 0
        },
        lineStyle: chartType.value === 'line' ? {
          color: '#42a5f5',
          width: 3,
          shadowColor: 'rgba(66, 165, 245, 0.5)',
          shadowBlur: 10,
        } : {},
        emphasis: {
          itemStyle: {
            color: '#ff7043',
            borderColor: '#ffccbc',
            borderWidth: 2,
          },
          focus: 'series'
        },
        showSymbol: chartType.value === 'line',
        symbolSize: 8,
        animationDelay: function (idx) {
          return idx * 100
        },
        animationDuration: 1500,
        animationEasing: 'elasticOut',
        // 平均线
        markLine: {
          data: [
            { type: 'average', name: '平均值' },
          ],
          lineStyle: {
            color: '#ff5722',
            width: 2,
            type: 'dashed',
          },
          label: {
            color: '#ff5722',
            formatter: '{b}: {c}'
          },
        },
      },
    ],
  })
}

// 时间筛选切换
const handleClick = async (type: string) => {
  try {
    if (type === 'day') {
      type1.value = 'success'
      type2.value = 'primary'
      type3.value = 'primary'
      await getIpAddressListByDate()
    } else if (type === 'month') {
      type1.value = 'primary'
      type2.value = 'success'
      type3.value = 'primary'
      await getIpAddressListByMonth()
    } else if (type === 'year') {
      type1.value = 'primary'
      type2.value = 'primary'
      type3.value = 'success'
      await getIpAddressListByYear()
    }
    
    updateChart()
  } catch (error) {
    console.error('切换时间筛选失败:', error)
  }
}

// 图表类型切换
const changeType = (type: string) => {
  chartType.value = type
  updateChart()
}

// 监听图表类型变化
watch(chartType, () => {
  if (dataLoaded.value) {
    updateChart()
  }
})

// 数据获取方法
const getUserCount = async () => {
  try {
    let res = await getAllUserCountSync()
    BoxData.value.push({
      title: '用户量',
      count: res.data.count,
      icon: 'm1',
    })
  } catch (error) {
    console.error('获取用户数据失败:', error)
  }
}

const getArticlesCount = async () => {
  try {
    let res = await getArticlesCountSync()
    BoxData.value.push({
      title: '文章数量',
      count: res.data.totalArticles,
      icon: 'm2',
    })
  } catch (error) {
    console.error('获取文章数据失败:', error)
  }
}

const getCommentsCount = async () => {
  try {
    let res = await getCommentsCountSync()
    BoxData.value.push({
      title: '评论数量',
      count: res.data.totalComments,
      icon: 'm3',
    })
  } catch (error) {
    console.error('获取评论数据失败:', error)
  }
}

const getCountIPAddress = async () => {
  try {
    let res = await countIPAddressSync()
    BoxData.value.push({
      title: '访问次数',
      count: res.data.data,
      icon: 'm4',
    })
  } catch (error) {
    console.error('获取IP地址数据失败:', error)
  }
}

// 窗口调整大小时，调用图表 resize
const resizeChart = () => {
  if (myChart) {
    myChart.resize()
  }
}
</script>

<style scoped lang="scss">
.analytics-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

// 统计卡片样式
.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 25px;
  
  @media (max-width: 1200px) {
    grid-template-columns: repeat(2, 1fr);
  }
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.stat-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  position: relative;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  }
  
  &-1 { background: linear-gradient(135deg, #42a5f5, #0d47a1); }
  &-2 { background: linear-gradient(135deg, #66bb6a, #1b5e20); }
  &-3 { background: linear-gradient(135deg, #ffa726, #e65100); }
  &-4 { background: linear-gradient(135deg, #ef5350, #b71c1c); }
  
  &-content {
    padding: 20px;
    color: white;
  }
  
  &-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    h3 {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
    }
  }
  
  &-value {
    margin: 20px 0;
    
    .count-number {
      font-size: 36px;
      font-weight: 700;
      display: block;
    }
  }
  
  &-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
    font-size: 14px;
    
    .label {
      opacity: 0.9;
    }
    
    .total-value {
      font-weight: 600;
      background: rgba(255, 255, 255, 0.2);
      padding: 4px 8px;
      border-radius: 12px;
    }
  }
}

.stat-icon {
  opacity: 0.9;
}

// 图表区域样式
.chart-section {
  margin-bottom: 25px;
}

.chart-card {
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  
  :deep(.el-card__header) {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
  }
  
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.time-filter {
  .filter-btn {
    font-weight: 500;
    transition: all 0.3s ease;
    
    &:hover {
      opacity: 0.9;
    }
  }
}

.chart-type-selector {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.chart-type-btn {
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  
  &.active {
    color: white;
    background-color: #409eff;
    border-color: #409eff;
  }
  
  i {
    margin-right: 5px;
  }
}

.chart-container {
  position: relative;
  min-height: 400px;
}

.chart-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.7);
  z-index: 1;
}

.echarts-container {
  width: 100%;
  height: 400px;
}

// 地图区域样式
.geo-section {
  margin-bottom: 25px;
  height: 650px; // 增加整体高度
}

.geo-card {
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  height: 100%; // 使用100%高度填充父容器
  display: flex;
  flex-direction: column;
  
  :deep(.el-card__body) {
    flex: 1;
    height: calc(100% - 60px);
    padding: 0;
    overflow: hidden; // 防止内容溢出
  }
}
</style>